package location.cn.org.wias.wifiscan;
import android.Manifest;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import location.cn.org.wias.wifiscan.entity.SpotData;

public class MainActivity extends AppCompatActivity {
    private TextView bssdiData;
    private EditText position;
    private Button submit;
    private int count=0;
    private  WifiManager mWifiManager ;
    private SpotData spotData = new SpotData();
    //private static final String NETWORKTYPE_WIFI = "http://172.16.33.6:8080/test";
    private static final String NETWORKTYPE_WIFI = "http://192.168.9.116:8080/manage/dataCollection";

    //点击提交，每2.5秒扫描一次wifi并上传，共扫描3次。
    private Handler mThreeHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //count 点击提交，上传的次数，现在是点击提交，上传三次
            if (msg.what == 0) {

                scanWifiState();
                //count++;
                sendPost();
                //每2.5秒调用次handler
                //mThreeHandler.sendEmptyMessageDelayed(0, 3000);
            }

        }
    };

    private void sendPost() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //bssidTest.setPosition(position.getText().toString());
                    HttpPost.Post(NETWORKTYPE_WIFI, spotData.toJson());
                    spotData.getRssi().clear();
                    SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    count++;
                    /*if(count<2){

                        mThreeHandler.sendEmptyMessageDelayed(0, 3000);
                    }

                    System.out.println(sd.format(new Date())+"----"+spotData.getSpot()+"---"+count+"---"+spotData.getRssi());*/

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    /**
     * 需要进行检测的权限数组
     */
    protected String[] needPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,

    };

    private static final int PERMISSON_REQUESTCODE = 0;
    private static final int SETTING_REQUESTCODE = 1;

    /**
     * 判断是否需要检测，防止不停的弹框
     */
    private boolean isNeedCheck = true;

    @Override
    protected void onResume() {
        super.onResume();
        if (isNeedCheck) {
            checkPermissions(needPermissions);
        }
    }

    /**
     * @param permissions
     * @since 2.5.0
     */
    private void checkPermissions(String... permissions) {
        List<String> needRequestPermissonList = findDeniedPermissions(permissions);
        if (null != needRequestPermissonList && needRequestPermissonList.size() > 0) {
            ActivityCompat.requestPermissions(this,
                    needRequestPermissonList.toArray( new String[needRequestPermissonList.size()]),
                    PERMISSON_REQUESTCODE);
        }
    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     * @since 2.5.0
     */
    private List<String> findDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissonList = new ArrayList<String>();
        for (String perm : permissions) {
            if (ContextCompat.checkSelfPermission(this,
                    perm) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.shouldShowRequestPermissionRationale( this, perm)) {
                needRequestPermissonList.add(perm);
            }
        }
        return needRequestPermissonList;
    } /**
     * 检测是否说有的权限都已经授权
     *
     * @param grantResults
     * @return
     * @since 2.5.0
     */
    private boolean verifyPermissions(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] paramArrayOfInt) {
        if (requestCode == PERMISSON_REQUESTCODE) {
            if (!verifyPermissions(paramArrayOfInt)) {
                showMissingPermissionDialog();
                isNeedCheck = false;
            }
        }
    }

    /**
     * 显示提示信息
     *
     * @since 2.5.0
     */
    private void showMissingPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.notifyTitle);
        builder.setMessage(R.string.notifyMsg);

        // 拒绝, 退出应用
        builder.setNegativeButton(R.string.cancel,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });

        builder.setPositiveButton(R.string.setting,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                });

        builder.setCancelable(false);

        builder.show();
    } /**
     * 启动应用的设置
     *
     * @since 2.5.0
     */
    private void startAppSettings() {
        Intent intent = new Intent( Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivityForResult(intent, SETTING_REQUESTCODE);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            this.finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SETTING_REQUESTCODE) {
            checkPermissions(needPermissions);
        }
    }




    private void registerBroadcast(){
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        this.registerReceiver(mBroadcastReceiver,intentFilter);
    }
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String resultAction = intent.getAction();
            //Log.e("收到wifi相关的广播：",sd.format(new Date())+","+resultAction);

            List<ScanResult> scanResults = mWifiManager.getScanResults();

            SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if(count<3){
                if(scanResults.size()>0){
                    for(ScanResult scanResult : scanResults) {

                        //bssid.put(scanResult.BSSID, WifiManager.calculateSignalLevel(scanResult.level, scanResult.level));
                        spotData.getRssi().put(scanResult.BSSID,scanResult.level);
                    }
                    Log.e("level",sd.format(new Date())+","+spotData.getSpot()+";"+spotData.getRssi().toString());
                    bssdiData.setText(spotData.getRssi().toString());

                }else{
                    scanWifiState();
                }
                mThreeHandler.sendEmptyMessageDelayed(0, 1000);
            }else {
                submit.setEnabled(true);
            }



        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bssdiData = findViewById(R.id.bssid);
        position = findViewById(R.id.position);
        submit=findViewById(R.id.submit);
        mWifiManager= (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        registerBroadcast();

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                submit.setEnabled(false);
                String s=position.getText().toString();
                if("".equals(s)){
                    position.setText("0");
                    s="0";
                }
                spotData.setSpot(Integer.valueOf(s));
                SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Log.e("SpotData",sd.format(new Date()));
                //initData("position=" + position.getText().toString() + ", bssid = " +bssdiData.getText().toString());
                count=0;
                //scanWifiState();
                //mThreeHandler.sendEmptyMessageDelayed(0,500);

                mWifiManager.startScan();


            }
        });

        //下一个
        findViewById(R.id.next).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(position.getText().toString().length() == 0) {
                    position.setText("1");
                } else {
                    position.setText(Integer.valueOf(position.getText().toString()) + 1 + "");
                }

            }
        });

        //上一个
        findViewById(R.id.on).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(position.getText().toString().length() == 0) {
                    position.setText("0");
                } else {
                    position.setText(Integer.valueOf(position.getText().toString()) - 1 + "");
                }
            }
        });


    }

    public void scanWifiState() {
        //spotData.getRssi().clear();
        WifiManager mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        mWifiManager.startScan();



    }

    private void initData(String std) {
        String filePath = "/sdcard/Test/";
        String fileName = "log.txt";
        Log.e("Post", std);
        writeTxtToFile(std, filePath, fileName);
    }

    // 将字符串写入到文本文件中
    public void writeTxtToFile(String strcontent, String filePath, String fileName) {
        //生成文件夹之后，再生成文件，不然会出错
        makeFilePath(filePath, fileName);

        String strFilePath = filePath+fileName;
        // 每次写入时，都换行写
        String strContent = strcontent + "\r\n";
        try {
            File file = new File(strFilePath);
            if (!file.exists()) {
                Log.d("TestFile", "Create the file:" + strFilePath);
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
            Log.e("TestFile", "Error on write File:" + e);
        }
    }

    // 生成文件
    public File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    // 生成文件夹
    public static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            Log.i("error:", e+"");
        }
    }



}
